import json
import random

import requests
from user.models import *
from payment.wx_pay import get_sign, trans_dict_to_xml, trans_xml_to_dict
from user.models import UserModel
import uuid
from bus.settings import alipay
from bus import settings
import qrcode

import paypalrestsdk


class WxPay:
    def __repr__(self, request):
        # 统一订单查询接口
        url = "https://api.mch.weixin.qq.com/pay/orderquery"
        out_trade_no = str(request.GET.get("img")[0:-4])  # 支付后的商户订单号
        key = '945bec9df3614cffb74e39aba8fbf7d7'  # 商户api密钥

        params = {
            'appid': 'wx092344a76b9979ff',  # APPID
            'mch_id': '1602932608',  # 商户号
            'out_trade_no': out_trade_no,  # 订单编号
            'nonce_str': 'ibuaiVcKdpRxkhJA'  # 随机字符串
        }
        sign = get_sign(params, key)  # 获取签名
        params.setdefault('sign', sign)  # 添加签名到参数字典
        xml = trans_dict_to_xml(params)  # 转换字典为XML
        response = requests.request('post', url, data=xml)  # 以POST方式向微信公众平台服务器发起请求
        data_dict = trans_xml_to_dict(response.content)  # 将请求返回的数据转为字典
        # print(data_dict)
        user_obj = UserModel.objects.filter(username=request.user.username)
        # 支付成功  订单未支付
        if data_dict.get("trade_state_desc") == "支付成功" and Recharge.objects.filter(
                order_id=data_dict.get("out_trade_no")).first().status == '1':
            Recharge.objects.filter(order_id=data_dict.get("out_trade_no")).update(status=2)
            user_obj.update(balance=user_obj.first().balance + int(data_dict.get("total_fee")))
        return 'ok'

    def pay(self, request):
        url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'  # 微信扫码支付接口
        key = '945bec9df3614cffb74e39aba8fbf7d7'  #
        total_fee = 1  # 支付金额，单位分
        body = '123'  # 商品描述
        out_trade_no = 'order_%s' % random.randrange(100000, 999999)  # 订单编号
        user = request.user
        pay_method = request.data.get("pay_method")
        total_amount = request.data.get("total_amount")
        data = {
            "user": user,
            "order_id": out_trade_no,
            "pay_method": int(pay_method),
            "total_amount": total_amount,
        }
        obj = Recharge.objects.create(**data)
        obj.save()
        params = {
            'appid': 'wx092344a76b9979ff',  # APPID
            'mch_id': '1602932608',  # 商户号
            'notify_url': 'http://wxpay.v3u.cn/wx_back/',  # 回调地址
            'product_id': 'goods_%s' % random.randrange(100000, 999999),  # 商品编号
            'trade_type': 'NATIVE',  # 支付类型（扫码支付）
            'spbill_create_ip': '114.254.176.137',  # 发送请求服务器的IP地址
            'total_fee': total_fee,  # 订单总金额
            'out_trade_no': out_trade_no,  # 订单编号
            'body': body,  # 商品描述
            'nonce_str': 'ibuaiVcKdpRxkhJA'  # 字符串
        }
        sign = get_sign(params, key)  # 获取签名
        params.setdefault('sign', sign)  # 添加签名到参数字典
        xml = trans_dict_to_xml(params)  # 转换字典为XML
        response = requests.request('post', url, data=xml)  # 以POST方式向微信公众平台服务器发起请求
        data_dict = trans_xml_to_dict(response.content)  # 将请求返回的数据转为字典
        # print(data_dict)
        qrcode_name = out_trade_no + '.png'  # 支付二维码图片保存路径
        if data_dict.get('return_code') == 'SUCCESS':  # 如果请求成功
            img = qrcode.make(data_dict.get('code_url'))  # 创建支付二维码片
            img.save('static/we_pay/' + qrcode_name)  # 保存支付二维码
        return {'img': qrcode_name}
        # return HttpResponse(json.dumps({'img': qrcode_name}))


class PayPal:
    def __repr__(self, request):
        # ?paymentId=PAYID-L7UHJGA6ED88532FU3155144&token=EC-6AR335876U336883C&PayerID=73S3E9HVESDX4
        paymentid = request.GET.get("paymentId")  # 订单id
        payerid = request.GET.get("PayerID")  # 支付者id
        print(payerid)
        print(paymentid)
        payment = paypalrestsdk.Payment.find(paymentid)
        if payment.execute({"payer_id": payerid}):
            payment_history = paypalrestsdk.Payment.all({"count": 10})
            print(payment_history.payments)
            # Recharge.objects.filter(order_id=data_dict.get("out_trade_no")).update(status=2)
            # user_obj = User.objects.filter(username=request.user.username)
            # user_obj.update(balance=user_obj.first().balance + int(data_dict.get("total_fee")))
            return "支付成功"
        else:
            print(payment.error)  # Error Hash
            return "支付失败"

    def pay(self, request):
        user = request.user
        pay_method = request.data.get("pay_method")
        total_amount = request.data.get("total_amount")
        total_amount = total_amount / 6.531
        total_amount = round(total_amount, 2)
        data = {
            "user": user,
            "order_id": uuid.uuid4(),
            "pay_method": int(pay_method),
            "total_amount": total_amount,
        }
        obj = Recharge.objects.create(**data)
        obj.save()
        paypalrestsdk.configure({
            "mode": "sandbox",  # sandbox代表沙盒
            "client_id": "AYXXU0zjJVvQMIEzG6NPLauHuiMJSAGN8wpOnu1T7gNCm4JMc4Nw7QcZSgKhSbHyUSHKnhZqQ-lsEm8l",
            "client_secret": "ECa2PqKtQ-dD2NYO0eunVG4pXPNWCakssPuufcaT0ZtpdTTxx0G4nza78NM2D1w0w8jduWsmL98nA6rq"
        })

        payment = paypalrestsdk.Payment({
            "intent": "sale",
            "payer": {
                "payment_method": "paypal"},
            "redirect_urls": {
                "return_url": "http://localhost:8000/pay/pay_back/",  # 支付成功跳转页面
                "cancel_url": "http://localhost:3000/pay/pay_back/"},  # 取消支付页面
            "transactions": [{
                # "item_list": {
                #     "items": [{
                #         "name": str(obj.order_id),
                #     }]},
                "amount": {
                    "total": total_amount,
                    "currency": "USD"},
                "description": "这是一个订单测试"}]})

        if payment.create():
            for link in payment.links:
                if link.rel == "approval_url":
                    approval_url = str(link.href)
                    print("Redirect for approval: %s" % (approval_url))
                    return {"url": approval_url}
        else:
            print(payment.error)
            return "支付失败"


class AliPay:
    def __repr__(self, request):
        data = request.data
        data.pop("sign")
        print(data)
        # orders_obj = Recharge.objects.get(order_id=data['out_trade_no'])
        # orders_obj.trade_no = data['trade_no']
        # orders_obj.status = 2
        # orders_obj.save()
        return {"code": 200, "msg": 'ok'}

    def pay(self, request):
        user = request.user
        pay_method = request.data.get("pay_method")
        total_amount = request.data.get("total_amount")
        data = {
            "user": user,
            "order_id": str(uuid.uuid4()),
            "pay_method": int(pay_method),
            "total_amount": total_amount,
        }
        obj = Recharge.objects.create(**data)
        subject = "余额充值"
        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            # 订单号
            out_trade_no=obj.order_id,
            # 金额
            total_amount=obj.total_amount,
            subject='subject',
            # 回调地址
            return_url=settings.RETURN_URL,
            # notify_url="http://localhost:8000/pay/ali_back/"  # 可选, 不填则使用默认notify url
        )
        obj.save()

        pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
        return {'data': {'pay_url': pay_url, 'msg': 'OK', "code": 200}}


# 工厂类
class Plant:
    @staticmethod
    def product_pay(why, request):
        # print(why)
        if why == 1:
            return AliPay()
        elif why == 2:
            return WxPay()
        elif why == 3:
            return PayPal()
        if why == "ali_back":
            a = AliPay()
            return a.__repr__(request)
        elif why == "wx_back":
            w = WxPay()
            return w.__repr__(request)
        elif why == "pay_back":
            p = PayPal()
            return p.__repr__(request)
